package com.ruoyi.web.controller.bussiness;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.AsyncUtils;
import com.ruoyi.entity.po.TPlayer;
import com.ruoyi.service.IPlayerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.util.Pair;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author chenhainan
 * @since 2024-12-08 17:57
 */
@Slf4j
@RestController
@RequestMapping("/player")
@Api(tags = "PC-3.选手管理")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class PlayerController extends BaseController {

    private final IPlayerService playerService;

    private final TransactionTemplate transactionTemplate;

    @GetMapping("/list")
    @ApiOperation("查询选手列表")
    public TableDataInfo list( TPlayer tPlayer) {
        startPage();
        List<TPlayer> list = playerService.selectPlayerList(tPlayer);
        AsyncUtils.consumeAsync(list, t -> {
            t.setFansCount(playerService.fansCount(t.getId()));
            t.setThermalValue(playerService.thermalValue(t.getId()));
            t.setExpireValue(playerService.expireValue(t.getId()));
            t.setLikeCount(playerService.likeCount(t.getId()));
            t.setDislikeCount(playerService.dislikeCount(t.getId()));
            t.setCommentsCount(playerService.commentsCount(t.getId()));
            t.setTweetsLikeCount(playerService.tweetsLikeCount(t.getId()));
            t.setTweetsCommentsCount(playerService.tweetsCommentsCount(t.getId()));
            t.setChatContainsCount(playerService.chatContainsCount(t.getId()));
            t.setPopularityValue(playerService.popularityValue(t.getId()));
            t.setFocusTime(playerService.focusTime(t.getId()));
        });
        return getDataTable(list);
    }


    @Valid
    @Log(title = "添加选手", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    @ApiOperation("新增选手")
    public AjaxResult addSave(@RequestBody TPlayer tPlayer) {
        return toAjax(playerService.addPlayer(tPlayer));
    }

    @Valid
    @Log(title = "修改选手", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    @ApiOperation("修改选手")
    public AjaxResult editSave(@RequestBody TPlayer tPlayer) {
        return toAjax(playerService.updatePlayer(tPlayer));
    }


    @Log(title = "删除选手", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    @ApiOperation("删除选手")
    public AjaxResult remove(String ids) {
        return toAjax(playerService.deleteTActivitySwitchByIds(ids));
    }

    @Log(title = "淘汰选手", businessType = BusinessType.UPDATE)
    @PostMapping("/eliminate")
    @ResponseBody
    @ApiOperation("淘汰选手")
    public AjaxResult eliminatePlayer(@RequestParam Integer playerId) {
        return toAjax(playerService.eliminatePlayer(playerId));
    }

    @Log(title = "上传选手自定义值", businessType = BusinessType.UPDATE)
    @PostMapping("/uploadCustomizeValue")
    @ResponseBody
    @ApiOperation("上传选手自定义值")
    public AjaxResult uploadCustomizeValue(@RequestParam("excel") MultipartFile file) {
        final var modifyPairs = new ArrayList<Pair<String, Double>>();
        try (final InputStream fis = file.getInputStream();
             final Workbook workbook = new XSSFWorkbook(fis)) {
            final Sheet sheet = workbook.getSheetAt(0);
            // 从第一行开始
            for (int i = 1; i < sheet.getLastRowNum(); i++) {
                final Row row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }
                final Cell nameCell = row.getCell(0);
                final Cell valueCell = row.getCell(1);
                if (nameCell != null && valueCell != null) {
                    modifyPairs.add(Pair.of(nameCell.getStringCellValue(), valueCell.getNumericCellValue()));
                }
            }
        } catch (IOException e) {
            log.error("读取上传选手自定义值 Excel 发生错误", e);
            return error("读取上传选手自定义值 Excel 发生错误");
        }
        if (modifyPairs.isEmpty()) {
            return success("上传的 excel 内容为空");
        }
        transactionTemplate.executeWithoutResult(status -> {
            for (Pair<String, Double> modifyPair : modifyPairs) {
                playerService.updateCustomizeValue(modifyPair.getFirst(), modifyPair.getSecond());
            }
        });
        return success("保存成功");
    }

}
